package com.pwt.utils;

import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * HttpClient
 *
 * @author zhangzedong
 * @version 1.0
 * @date 2021/6/8
 */
@Component
public class HttpClientUtils {

    /**
     * get 请求
     *
     * @param baseUrl 请求地址
     * @return JSONArray
     */
    public JSONArray httpGet(String baseUrl) {
        JSONArray resData = null;
        try {
            URL url = new URL(baseUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            resData = JSONArray.parseArray(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
        return resData;
    }


}
